const { getList, getDetail, newBlog, updateBlog, delBlog } = require('../controller/blog');
const { SuccessModel, ErrorModel } = require('../model/resModel');

const loginCheck = req => {
  if(!req.session.username) {
    return Promise.resolve(new ErrorModel('尚未登陆'));
  }
}

const handleBlogRouter = (req, res) => {
  const method = req.method;
  const url = req.url;
  const path = url.split('?')[0];
  const id = req.query.id || '';

  if(method === 'GET' && path === '/api/blog/list') {
    const author = req.query.author || '';
    const keyword = req.query.keyword || '';
    const result = getList(author, keyword);

    return result.then(list => {
      return new SuccessModel(list, '获取博客列表成功！');
    })
  }

  if(method === 'GET' && path === '/api/blog/detail') {
    const detailRes = getDetail(id);

    return detailRes.then(detail => {
      return new SuccessModel(detail, '获取博客详情成功！');
    })
  }

  if(method === 'POST' && path === '/api/blog/new'){
    const loginResult = loginCheck(req);
    if(loginResult) {
      return loginResult;
    }
    req.payload.author = req.session.username;
    const dataRes = newBlog(req.payload);
    return dataRes.then(newBlog => {
      return new SuccessModel(newBlog, '创建博客成功！');
    })
  }

  if(method === 'POST' && path === '/api/blog/update') {
    const loginResult = loginCheck(req);
    if(loginResult) {
      return loginResult;
    }
    const result = updateBlog(id, req.payload);

    return result.then(updateBlog => {
      if(updateBlog) {
        return new SuccessModel(updateBlog, '更新博客成功！');
      }else {
        return new ErrorModel(updateBlog, '更新博客失败！');
      }
    })

  }

  if(method === 'POST' && path === '/api/blog/delete') {
    const loginResult = loginCheck(req);
    if(loginResult) {
      return loginResult;
    }

    req.payload.author = req.session.username;
    const result = delBlog(id, req.payload.author);

    return result.then(deleteBlog => {
      if(deleteBlog) {
        return new SuccessModel(deleteBlog, '删除博客成功！');
      }else {
        return new ErrorModel(deleteBlog, '删除博客失败！');
      }
    })
  }
}

module.exports = handleBlogRouter;
